import Web3 from "web3";
export default {
	web3:null,
	getWeb3({url=''}){
		return new Promise((resolve,reject)=>{
			
			
			let web3;
			if (window.ethereum) {
			  // use MetaMask's provider
			  web3 = new Web3(window.ethereum);
			  window.ethereum.enable(); // get permission to access accounts
			  
			} else {
			  console.warn(
			    "No web3 detected. Falling back to"+url+" . You should remove this fallback when you deploy live"
			  );
			  // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
			  web3 = new Web3(
			    new Web3.providers.HttpProvider(url)
			  );
			  reject("No web3 detected. Falling back to"+url+" . You should remove this fallback when you deploy live")
			}
			this.web3 = web3;
			resolve(this);
				
			
		})
	},
	toWei(arg) {
	  return new Promise((resolve, reject) => {
		let {web3} = this;
	    arg = web3.utils.toWei(arg.toString())
	    resolve(arg)
	  })
	},
	fromWei(arg) {
	  return new Promise((resolve, reject) => {
		let {web3} = this;
	    arg = web3.utils.fromWei(arg.toString())
	    resolve(arg)
	  })
	},
	
	async addChain(data){
			  try {
			    await ethereum.request({
			      method: 'wallet_addEthereumChain',
			      params: [data],
			    });
			  } catch (addError) {
			  				  console.log(addError)
			    // handle "add" error
			  }
	},
	
	
	async switchChain(data){
		  try {
				  let {chainId} = data;
		    await ethereum.request({
		      method: 'wallet_switchEthereumChain',
		      params: [{ chainId }],
		    });
		  } catch (switchError) {
		    // This error code indicates that the chain has not been added to MetaMask.
				console.log(switchError)
		    if (switchError.code === 4902) {
		      
				  this.addChain(data);
		    }
		    // handle other "switch" errors
		  }
	},
  
  changed(){
  	let ethereum = window.ethereum;
  	if (typeof  ethereum !== 'undefined' || (typeof window.web3 !== 'undefined')) {
  	    ethereum.on('accountsChanged', function (accounts) {

  	        
  	        window.location.reload()

  	    })
  	    ethereum.on('chainChanged', function (chainId) {
  	        
  	        window.location.reload()
  	    })
  	    ethereum.on('networkChanged', function (networkVersion) {

  	        
  	        window.location.reload()

  	    })
  	}else {
  	    alert('You have to install MetaMask !')
  	}
  }
	
}